#version 400

out vec4 FragColor;
in vec3 gFacetNormal;
in vec3 gVertexNormal;
in vec3 gTriDistance;
in vec3 gPatchDistance;
in float gPrimitive;
in vec3 colorGeom;
in vec3 gLightDir;
in vec3 gPosition;
in vec3 gWireframeColor;

uniform vec3 LightPosition;
uniform vec3 DiffuseMaterial;
uniform vec3 AmbientMaterial;
uniform bool wireframeON;

float amplify(float d, float scale, float offset)
{
    d = scale * d + offset;
    d = clamp(d, 0, 1);
    d = 1 - exp2(-2*d*d);
    return d;
}

void main()
{
	//UpScreen y, RightScreen x, Into screen z
	//float test = dot(normalize(gLightDir), normalize(vec3(gFacetNormal.xyz)));
	//==============( Flat ligthing )=======================
	/*float distance = length(gLightDir);
	distance = distance * distance;
	vec3 lightDir = normalize(gLightDir);
	vec3 vertexNormal = normalize(gVertexNormal);
	float i = dot(lightDir, normalize(vertexNormal));
	float diffusePower = 2.0f;
	vec3 diffuse = i* vec3(1.0f, 0.0f, 0.0f) * diffusePower/distance;
	vec3 viewDir = lightDir;
	vec3 h = normalize(lightDir + viewDir);
	float specularHardness = 10.0f;
	i = pow(dot(vertexNormal, h), specularHardness);
	float specularPower = 2.0f;
	vec3 specular = i*vec3(1.0f, 1.0f, 1.0f)*specularPower/distance;
	vec3 ambient = vec3(0.4f, 0.0f, 0.0f);
    vec3 N = vertexNormal;
    vec3 L = LightPosition;
    float df = abs(dot(N, L));
    //vec3 color = AmbientMaterial + df * DiffuseMaterial;
	vec3 color = ambient + diffuse + specular;//colorGeom;// vec3(1.0, 0.0, 0.0);
	*/

	//=============( Phong ligthing )========================
	vec3 L = normalize(gLightDir);
	vec3 E = -L;// -normalize(gPosition); //might be *-1
	//vec3 N = normalize(gVertexNormal);
	vec3 N = normalize(gFacetNormal);//gFacetNormal for nice effect
	vec3 R = normalize(reflect(L,N));

	vec4 Iamb = vec4(0.0f, 0.0f, 0.2f, 1.0f);
	
	vec4 Idiff = vec4(0.0f, 0.0f, 0.4f, 1.0f)*max(dot(N,L), 0.0);
	Idiff = clamp(Idiff, 0.0, 1.0);

	float shininess = 20.0f;
	vec4 Ispec = vec4(1.0f, 1.0f, 1.0f, 1.0f)*pow(max(dot(R,E), 0.0f), 0.1f*shininess);
	Ispec = clamp(Ispec, 0.0f, 1.0f);

	vec3 color = clamp((Iamb + Idiff + Ispec).xyz, 0.0f, 1.0f);
	//==============( Wireframe )=================
    float d1 = min(min(gTriDistance.x, gTriDistance.y), gTriDistance.z);
    float d2 = min(min(gPatchDistance.x, gPatchDistance.y), gPatchDistance.z);
	if(wireframeON)
	{
		d1 = 1 - amplify(d1, 50, -0.5);
		d2 = amplify(d2, 60, -0.5);
		color = d2 * color + d1*d2*gWireframeColor;
	}
	
    FragColor = vec4(color, 1.0);
}


/*
in vec3 pass_Color;

out vec4 out_Color;

void main()
{
	//out_Color = vec4(pass_Color, 1.0);
	out_Color = vec4(1.0, 1.0, 1.0, 1.0);
}
*/